<script setup>
import { useDish } from "@/views/Category/composables/useDish.js";
import { ref, onMounted, watch } from "vue";
import {useCartStore} from "@/stores/cartStore.js";
const cartStore = useCartStore()
const { dishList } = useDish();
// 为每个菜品创建独立的数量引用
const dishCounts = ref({});

// 确保dishList是数组的安全处理函数
const safeDishList = () => {
  // 如果dishList不存在或不是数组，返回空数组
  if (!dishList || !Array.isArray(dishList.value)) {
    return [];
  }
  return dishList.value;
};

// 初始化或更新菜品数量
const initDishCounts = () => {
  const dishes = safeDishList();
  dishes.forEach(dish => {
    // 只初始化未设置过的菜品数量
    if (dishCounts.value[dish.id] === undefined) {
      dishCounts.value[dish.id] = 0;
    }
  });
};

// 初始加载时初始化
onMounted(initDishCounts);

// 监听dishList变化，动态更新计数
watch(
    () => dishList.value,
    () => {
      initDishCounts();
    },
    { deep: true } // 深度监听，应对数组内容变化
);

// 更新菜品数量的方法
const updateCount = (dishId, value) => {
  console.log(value,dishId);
  dishCounts.value[dishId] = value;
  cartStore.addCart(dishId);

};

</script>

<template>
  <div class="dish-container">
    <!-- 加载状态提示 -->
    <div v-if="!safeDishList().length" class="loading">
      该商品已下架,换一个试一试
    </div>

    <ul class="dish-list" v-else>
      <li v-for="dish in safeDishList()" :key="dish.id" class="dish-item">
        <div class="dish-image">
          <img :src="dish.image" :alt="dish.name" class="food-img">
        </div>
        <div class="dish-info">
          <h3 class="dish-name">{{ dish.name }}</h3>
          <p class="dish-description">{{ dish.description }}</p>
          <p class="dish-price">&yen;{{ dish.price.toFixed(2) }}</p>
        </div>
        <div class="dish-quantity">
          <el-input-number
              size="small"
              v-model="dishCounts[dish.id]"
              @change="(value) => updateCount(dish.id, value)"
              :min="0"
              label="数量"
          ></el-input-number>
        </div>
      </li>
    </ul>
  </div>
</template>

<style scoped>
.dish-container {
  padding: 0.2rem;
  height: 10rem;
  overflow: auto; /*内容超出添加滚动条*/
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.dish-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.dish-item {
  display: flex;
  align-items: center;
  padding: 0.05rem;
  border-bottom: 0.1rem solid #eee;
  transition: background-color 0.3s ease;
}

.dish-item:hover {
  background-color: #f8f9fa;
}

.dish-image {
  flex: 0 0 1rem;
  margin-right: 0.15rem;
}

.food-img {
  width: 2rem;
  height: 2rem;
  object-fit: cover;
  border-radius: 8px;
}

.dish-info {
  flex: 1;
}

.dish-name {
  margin: 0 0 8px 0;
  font-size: 0.3rem;
  font-weight: 600;
}

.dish-description {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 0.25rem;
  line-height: 1.4;
}

.dish-price {
  margin: 0;
  color: #f56c6c;
  font-weight: 600;
}

.dish-quantity {
  flex: 0 0 auto;
}
</style>
